package com.citsin.atlas.adapter

import android.content.ContentUris
import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.citsin.atlas.R
import com.citsin.atlas.bean.Media

/**
 * citsin
 * 2019-06-04
 */
class MediaListAdapter(private val context: Context) : PagedListAdapter<Media, MediaListAdapter.MediaItemViewHolder>(diffCallback) {

    private val inflater = LayoutInflater.from(context)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MediaItemViewHolder {
        return MediaItemViewHolder(inflater.inflate(R.layout.item_media, parent, false))
    }

    override fun onBindViewHolder(holder: MediaItemViewHolder, position: Int) {
        val item = getItem(position)

        Glide.with(context).load(Uri.parse(item!!.uri)).into(holder.imageView)
        holder.itemView.setOnClickListener { listener(position,item) }

    }

    fun setOnItemClickListener(e: (Int, Media?) -> Unit) {
        this.listener = e
    }
    private var listener: (Int, Media?) -> Unit = { _, _ ->}

    inner class MediaItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        val imageView:ImageView = itemView.findViewById(R.id.imageView)
    }

    companion object {
        private val diffCallback = object : DiffUtil.ItemCallback<Media>() {
            override fun areItemsTheSame(oldItem: Media, newItem: Media): Boolean {
                return oldItem.id === newItem.id
            }

            override fun areContentsTheSame(oldItem: Media, newItem: Media): Boolean {
                return oldItem == newItem
            }
        }
    }
}
